<?php

declare(strict_types=1);

namespace app\command;

use app\common\config\model\ConfigHall;
use app\common\config\model\ConfigSource;
use app\common\config\model\ConfigStore;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerContact;
use app\common\order\model\Order;
use app\common\system\model\User;
use PDO;
use PDOException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Sync extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync')
            ->addOption('type', null, Option::VALUE_REQUIRED, 'sync type')
            ->addOption('fileName', null, Option::VALUE_OPTIONAL, "the file name")
            ->setDescription('the sync command');
    }

    protected function execute(Input $input, Output $output)
    {
        $type = $input->getOption('type');
        switch ($type) {
            case 'store':
                $this->syncStore($input, $output);
                break;

            case 'user':
                $this->syncUser($input, $output);
                break;

            case 'order':
                $this->syncOrder($input, $output);
                break;
            default:
                break;
        }
    }

    private function syncStore($input, $output)
    {
        // 读取 ./data/staff.txt 文件
        $lines = file('./data/store-rs.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        print_r($lines);

        $model = new ConfigStore();

        $hotelMatches = [
            7 => [
                'keys' => ['万豪', '正佳'],
                'condition' => 'and'
            ],
            9 => [
                'keys' => ['东圃', '喜来登'],
                'condition' => 'and'
            ],
            15 => [
                'keys' => ['文化东方'],
                'condition' => 'and'
            ],
            21 => [
                'keys' => ['粤海', '喜来登'],
                'condition' => 'and'
            ],
            45 => [
                'keys' => ['奥园'],
                'condition' => 'and'
            ],
            62 => [
                'keys' => ['未知', '还没定', '增城新好景', '椰林盛宴', '金城潮州', '茂名信宜莲花湖温德姆', '信宜莲花湖温德姆', '北洛秘境'],
                'condition' => 'or'
            ],
            1 => [
                'keys' => ['海航', '威斯丁'],
                'condition' => 'and'
            ],
            36 => [
                'keys' => ['保利', '假日'],
                'condition' => 'and'
            ],
            64 => [
                'keys' => ['中西名菜'],
                'condition' => 'and'
            ],
            51 => [
                'keys' => ['广', '酒', '白云'],
                'condition' => 'and'
            ],
            58 => [
                'keys' => ['昌岗', '达镖'],
                'condition' => 'or'
            ],
            61 => [
                'keys' => ['白云', '万豪'],
                'condition' => 'and'
            ],
            68 => [
                'keys' => ['渔民新村'],
                'condition' => 'and'
            ],
            27 => [
                'keys' => ['香岚王子', '香岚'],
                'condition' => 'or'
            ],
            24 => [
                'keys' => ['郎豪', '朗豪'],
                'condition' => 'or'
            ],
            39 => [
                'keys' => ['君澜'],
                'condition' => 'and'
            ],
            65 => [
                'keys' => ['木莲庄'],
                'condition' => 'and'
            ],
            53 => [
                'keys' => ['长隆'],
                'condition' => 'and'
            ],
            78 => [
                'keys' => ['富临皇宫'],
                'condition' => 'and'
            ],
            71 => [
                'keys' => ['kitchen'],
                'condition' => 'and'
            ],
            69 => [
                'keys' => ['伊斯丹顿酒店'],
                'condition' => 'and'
            ],
            79 => [
                'keys' => ['京华保利广场店'],
                'condition' => 'and'
            ],
            82 => [
                'keys' => ['沙面火车头'],
                'condition' => 'and'
            ],
            83 => [
                'keys' => ['半山茶园'],
                'condition' => 'and'
            ],
            84 => [
                'keys' => ['南沙喜来登'],
                'condition' => 'and'
            ],
            67 => [
                'keys' => ['和苑'],
                'condition' => 'and'
            ],
            87 => [
                'keys' => ['岑溪'],
                'condition' => 'and'
            ],
            88 => [
                'keys' => ['美丽豪'],
                'condition' => 'and'
            ],
            93 => [
                'keys' => ['皇潮'],
                'condition' => 'and'
            ],
            95 => [
                'keys' => ['温德姆'],
                'condition' => 'and'
            ],
            97 => [
                'keys' => ['喜爱轩'],
                'condition' => 'and'
            ],
        ];

        // 将每行匹配到的用户ID做好映射
        $storeMap = [];
        foreach ($lines as $line) {
            $line = trim($line);
            foreach ($hotelMatches as $key => $hotelMatch) {
                if ($hotelMatch['condition'] == 'and') {
                    $match = true;
                    foreach ($hotelMatch['keys'] as $hotelKey) {
                        if (strpos($line, $hotelKey) === false) {
                            $match = false;
                            break;
                        }
                    }
                    if ($match) {
                        $storeMap[$line] = $key;
                        continue 2;
                    }
                } else {
                    $match = false;
                    foreach ($hotelMatch['keys'] as $hotelKey) {
                        if (strpos($line, $hotelKey) !== false) {
                            $match = true;
                            break;
                        }
                    }
                    if ($match) {
                        $storeMap[$line] = $key;
                        continue 2;
                    }
                }
            }

            $hotelTitle = str_replace('万白云富', '白云万富', $line);
            // 将包含“正佳”但不包含"正佳广场" 替换成"正佳广场"
            if (strpos($hotelTitle, '正佳') !== false && strpos($hotelTitle, '正佳广场') === false) {
                $hotelTitle = str_replace('正佳', '正佳广场', $hotelTitle);
            }
            $hotelName = preg_replace('/(广州市|广州|大酒店|酒家|酒店|酒楼)/', '', $hotelTitle);
            $row = $model->whereLike('title', "%$hotelName%")->find();
            if ($row) {
                $storeMap[$line] = $row['id'];
            } else {
                $storeMap[$line] = 0;
            }
        }

        // 将php数组代码保存到文件
        $code = "<?php\n\n";
        $code .= "return " . var_export($storeMap, true) . ";\n\n";
        file_put_contents('./data/store.php', $code);

        // 将未匹配到的酒店写入到csv文件
        $fp = fopen('./data/notMatchedHotel.csv', 'w');
        foreach ($storeMap as $key => $value) {
            if ($value == 0) {
                fputcsv($fp, [$key]);
            }
        }
        fclose($fp);
    }

    private function syncUser($input, $output)
    {
        // 读取 ./data/staff.txt 文件
        $lines = file('./data/staff-rs.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        print_r($lines);

        $userModel = new User();

        // 将每行匹配到的用户ID做好映射
        $userMap = [];
        foreach ($lines as $line) {
            $line = trim($line);
            // $line正则匹配英文
            if (preg_match("/[a-zA-Z]+/", $line, $matches)) {
                $user = $userModel->whereLike('realname|nickname', "%{$matches[0]}%")->find();
            } else {
                $user = $userModel->whereLike('realname|nickname', "%{$line}%")->find();
            }


            if ($user) {
                $userMap[$line] = $user['id'];
            } else {
                $userMap[$line] = 0;
            }
        }

        // 将php数组代码保存到文件
        $code = "<?php\n\n";
        $code .= "return " . var_export($userMap, true) . ";\n\n";
        file_put_contents('./data/staff.php', $code);
    }

    private function syncOrder($input, $output)
    {
        $now = date('Y-m-d H:i:s');
        $fileName = $input->getOption('fileName');
        if (empty($fileName)) {
            $output->writeln('请输入文件名');
            return;
        }

        $staffs = include('data/array-user.php');
        $hotels = include('data/store.php');
        $numbers = include('data/mobile.php');
        // print_r($staffs);

        $cates = [
            "婚宴信息" => 1,
            "婚庆信息" => 2,
            "一站式" => 4,
            "活动/会务" => 3,
            "宝宝宴" => 10,
        ];

        // 合作模式
        $cooperationModes = [
            "代收代付" => 1,
            "一单一议" => 5,
            "返佣单" => 3,
            "代收代付+返佣" => 2,
            "婚庆" => 4,
        ];

        $orderTypes = [
            "订单" => 1,
            "定金" => 3,
            "意向金" => 4,
            "返佣单" => 2
        ];

        $companyMap = [
            "广州诚家文化" => 3,
            "广州鸿泰酒店管理" => 2,
            "广州喜觅文化传播" => 1,
            "广州馨悦文化传播" => 4,
        ];

        // 指令输出
        // 读取./data/1.xlsx文件
        $file = './data/' . $fileName . '.xlsx';
        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $spreadsheet = $reader->load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数
        $hotelModel = new ConfigStore();
        $hallModel = new ConfigHall();
        $dictModel = new ConfigSource();
        $contactModel = new CustomerContact();

        $notMatchedHotel = [];
        $notMatchedHall = [];
        // 将orderData 写入到csv文件
        for ($row = 2; $row <= $highestRow; $row++) {
            $orderData = [];
            // 订单编号
            $orderData['order_no'] = $sheet->getCell('A' . $row)->getValue();
            if (isset($numbers[$orderData['order_no']])) {
                if (empty($numbers[$orderData['order_no']])) continue;
                $contactPhone = $numbers[$orderData['order_no']];
            } else {
                // 联系人
                $contactName = $sheet->getCell('C' . $row)->getValue();
                // 联系人电话
                $contactPhone = $sheet->getCell('H' . $row)->getValue();
                // $phone = str_replace('****', '%', $contactPhone);
                // echo $phone;
            }

            $contact = $contactModel->where('contact', $contactPhone)->find();
            if (empty($contact)) {
                print_r($contact);
                continue;
            }

            // 跟单人
            $kefu = $sheet->getCell('K' . $row)->getValue();


            // 订单来源
            $source = $sheet->getCell('J' . $row)->getValue();
            // 回款金额
            $orderData['member_id'] = $contact['member_id'];

            // 商品名称
            // $goodsName = $sheet->getCell('Y' . $row)->getValue();
            // 商品备注
            // $goodsRemark = $sheet->getCell('AA' . $row)->getValue();
            // 商品类别
            // $goodsCate = $sheet->getCell('AB' . $row)->getValue();


            // 订单基本信息

            $createUser = $sheet->getCell('O' . $row)->getValue();
            // 订单创建人
            if ($createUser instanceof \PhpOffice\PhpSpreadsheet\RichText\RichText) {
                $createUser = $createUser->getPlainText();
            }

            $allocateModel = new CustomerAllocate();
            if (isset($staffs[$createUser])) {
                $userId = $staffs[$createUser];
                $orderData['user_id'] = $userId;
                $allocate = $allocateModel->where('user_id', $userId)->where('member_id', $contact['member_id'])->find();
                if (empty($allocate)) {
                    $allocateData = [];
                    $allocateData['from_user_id'] = 1;
                    $allocateData['user_id'] = $userId;
                    $allocateData['member_id'] = $contact['member_id'];
                    $allocateData['create_time'] = $now;
                    $allocateModel->save($allocateData);
                    $orderData['allocate_id'] = $allocateModel->id;
                    echo 'orderNo:' . $orderData['order_no'] . "\n";
                } else {
                    $orderData['allocate_id'] = $allocate['id'];
                }
            } else {
                $orderData['user_id'] = 0;
            }

            // 创建人部门
            $createDept = $sheet->getCell('P' . $row)->getValue();
            // 订单公司
            $companyName = $sheet->getCell('AG' . $row)->getValue();
            $orderData['company_id'] = $companyMap[$companyName] ?? 0;

            // 订单状态
            $orderData['check_status'] = 2;
            // 订单类型
            $categoryText = $sheet->getCell('AH' . $row)->getValue();
            $categoryId = $cates[$categoryText] ?? 0;

            if (empty($categoryId)) continue; // 如果没有订单类型则跳过(一站式订单
            $orderData['category_id'] = $categoryId;

            // 订单性质
            $orderType = $sheet->getCell('AI' . $row)->getValue();
            if (!isset($orderTypes[$orderType])) continue;
            $orderData['order_type'] =  $orderTypes[$orderType];
            // 合作模式
            $cooperationMode = $sheet->getCell('AJ' . $row)->getValue();
            $orderData['cooperation_id'] = $cooperationModes[$cooperationMode] ?? 0;
            // 订单合同编号
            $orderData['contract_no'] = $sheet->getCell('AK' . $row)->getValue();
            // 酒店名称
            $hotelTitle = $sheet->getCell('AL' . $row)->getValue();
            if (isset($hotels[$hotelTitle])) {
                $hotelId = $hotels[$hotelTitle];
            } else {
                $hotelId = 0;
            }
            $orderData['store_id'] = $hotelId;

            // 宴会厅
            $hallName = $sheet->getCell('AM' . $row)->getValue();
            if ($hotelId > 0) {
                $hall = $hallModel->where('store_id', $hotelId)->where('title', $hallName)->find();
                $orderData['hall_id'] = $hall['id'] ?? 0;
                if (empty($hall)) {
                    $notMatchedHall[] = $hotelTitle . ":" . $hallName;
                }
            } else {
                $orderData['hall_id'] = 0;
                $notMatchedHotel[] = $hotelTitle . ":" . $hotelName;
            }

            // 宴会类型
            $banquetType = $sheet->getCell('AN' . $row)->getValue();
            $orderData['banquet_type_id'] = $banquetType == '午宴' ? 1 : 2;

            // 新郎姓名、电话
            $groom = $sheet->getCell('AO' . $row)->getValue();
            $groom = $this->formatCustomer($groom);
            $orderData['bridegroom'] = $groom['name'];
            $orderData['bridegroom_mobile'] = $groom['phone'];

            // 新娘姓名、电话
            $bride = $sheet->getCell('AP' . $row)->getValue();
            $bride = $this->formatCustomer($bride);
            $orderData['bride'] = $bride['name'];
            $orderData['bride_mobile'] = $bride['phone'];
            // 签约时间
            $orderData['sign_date'] = $sheet->getCell('AQ' . $row)->getValue();
            // 举办时间
            $orderData['event_date'] = $sheet->getCell('AR' . $row)->getValue();
            // 联系地址
            $orderData['address'] = $sheet->getCell('AS' . $row)->getValue();
            // 身份证号
            $orderData['id_card'] = $sheet->getCell('AT' . $row)->getValue();
            // 下单时间
            $createTime = $sheet->getCell('D' . $row)->getValue();
            $orderData['create_time'] = strtotime($createTime);
            // 备注
            $orderData['remark'] = $sheet->getCell('U' . $row)->getValue() . $sheet->getCell('AY' . $row)->getValue();
            // 订单凭证
            $files = $sheet->getCell('T' . $row)->getValue();
            $orderData['files'] = $this->formatFiles($files);
            $totals = $sheet->getCell('AE' . $row)->getValue();
            $orderData['totals'] = $totals;
            $orderData['check_time'] = $now;
            $orderModel = new Order();
            $orderModel->save($orderData);


            $orderId = $orderModel->id;
            // 订单商品信息
            $goodsRemark = $sheet->getCell('AA' . $row)->getValue();

            if ($orderTypes[$orderType] == 2) {
                // 返佣单
                $settleModel = new \app\common\order\model\OrderSettle();
                $settleData = [];
                $settleData['order_id'] = $orderId;
                $price = (float)$sheet->getCell('AU' . $row)->getValue();
                $amount = (float)$sheet->getCell('AV' . $row)->getValue();
                $settleData['company_id'] = $companyMap[$companyName];
                $settleData['user_id'] = $staffs[$createUser] ?? 0;
                $settleData['price'] = $price;
                $settleData['amount'] = $amount;
                $settleData['total'] = $price * $amount;
                $settleData['category_id'] = $categoryId == 4 ? 1 : $categoryId;
                $settleData['remark'] = $goodsRemark;
                // print_r($settleData);         
                $settleModel->save($settleData);


            } else {
                // 婚宴餐标
                $price = (float)$sheet->getCell('AU' . $row)->getValue();
                if ($categoryId != 2) {
                    $goodsData = [];
                    $goodsData['company_id'] = $companyMap[$companyName];
                    $goodsData['order_id'] = $orderId;
                    $goodsData['price'] = $price;
                    // 婚宴桌数
                    $goodsData['amount'] = $sheet->getCell('AV' . $row)->getValue();
                    // 转化为数字类型
                    $amount = (float)$goodsData['amount'];
                    $goodsData['total'] = $amount * $price;
                    $goodsData['category_id'] = $categoryId == 4 ? 1 : $categoryId; // 一站式订单的婚宴餐标归类到婚宴信息
                    $goodsData['remark'] = $goodsRemark;

                    $orderProductModel = new \app\common\order\model\OrderProduct();
                    $orderProductModel->save($goodsData);
                }

                // 婚庆套餐
                // $goodsData['wedding_package'] = $sheet->getCell('AW' . $row)->getValue();
                // 婚庆实收价格
                $weddingTotal = (float)$sheet->getCell('AX' . $row)->getValue();
                if ($categoryId == 4 || $categoryId == 2) {
                    $goodsData = [];
                    $goodsData['company_id'] = $companyMap[$companyName];
                    $goodsData['order_id'] = $orderId;
                    $goodsData['total'] = $weddingTotal > 0 ? $weddingTotal : $orderData['totals'];
                    $goodsData['category_id'] = 2;
                    $goodsData['remark'] = $goodsRemark;
                    $orderProductModel = new \app\common\order\model\OrderProduct();
                    $orderProductModel->save($goodsData);
                }
            }


            // 收款计划
            $collects = [];
            // 定金收款计划
            $collectItem = [];
            $collectItem['order_id'] = $orderId;
            $collectItem['price'] = $sheet->getCell('AZ' . $row)->getValue(); // 定金金额
            $collectItem['collect_date'] = $sheet->getCell('BA' . $row)->getValue(); // 定金回款时间
            $collectItem['type'] = 1;
            $collectItem['complete'] = 100;
            $collects[] = $collectItem;
            // 中款收款计划
            $collectItem = [];
            $collectItem['order_id'] = $orderId;
            $collectItem['price'] = $sheet->getCell('BB' . $row)->getValue(); // 中款金额
            $collectItem['collect_date'] = $sheet->getCell('BC' . $row)->getValue(); // 中款回款时间
            $collectItem['type'] = 2;
            $collectItem['complete'] = 100;
            $collects[] = $collectItem;
            // 尾款收款计划
            $collectItem = [];
            $collectItem['order_id'] = $orderId;
            $collectItem['price'] = $sheet->getCell('BD' . $row)->getValue(); // 尾款金额
            $collectItem['collect_date'] = $sheet->getCell('BE' . $row)->getValue(); // 尾款回款时间
            $collectItem['type'] = 3;
            $collectItem['complete'] = 100;
            $collects[] = $collectItem;
            // 添加返佣收款计划
            $collectModel = new \app\common\order\model\OrderCollect();
            $collectModel->saveAll($collects);


            // 收款记录
            $income = [];
            // $orderData['pay_amount'] = $sheet->getCell('R' . $row)->getValue();
            // 已收款金额/未收款金额
            $income['order_id'] = $orderId;
            $income['total'] = $sheet->getCell('R' . $row)->getValue();
            $income['income_way_id'] = 7;
            $income['income_type_id'] = 1;
            $incomeModel = new \app\common\order\model\OrderIncome();
            $incomeModel->save($income);
        }
    }

    private function formatCustomer($customer)
    {
        // 正则匹配姓名
        preg_match('/[\x{4e00}-\x{9fa5}]+/u', $customer, $matches);
        // 正则匹配电话 138 2600 768
        preg_match('/1[3456789]\d{9}/', $customer, $phoneMatches);
        $customerName = $matches[0] ?? '';
        $customerPhone = $phoneMatches[0] ?? '';

        return [
            'name' => $customerName,
            'phone' => $customerPhone,
        ];
    }

    private function formatFiles($files)
    {
        $files = explode('、', $files);
        $result = [];
        foreach ($files as $file) {
            $extname = pathinfo($file, PATHINFO_EXTENSION);
            $filename = pathinfo($file, PATHINFO_FILENAME);
            $result[] = [
                'extname' => $extname,
                'filename' => $filename,
                'url' => $file,
            ];
        }
        return $result;
    }
}
